package top.hepingan.java.Apple;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.hepingan.java.entity.MemberOrder;
import top.hepingan.java.entity.emnu.PayStatus;
import top.hepingan.java.mapper.MemberOrderMapper;
import top.hepingan.java.utils.HttpClientUtil;

import java.time.LocalDateTime;

/**
 * 用户在 iOS App 内使用 StoreKit 购买。
 * App 拿到苹果返回的 receipt-data。
 * App 把 receipt-data 发给你服务端。
 * 服务端请求 Apple 验证接口（sandbox 或 production）。
 * Apple 返回结果，后端根据返回内容更新订单。
 * @author cxyck
 */
@Service
public class ApplePayService {
    private static final String APPLE_PRODUCTION_URL = "https://buy.itunes.apple.com/verifyReceipt";
    private static final String APPLE_SANDBOX_URL = "https://sandbox.itunes.apple.com/verifyReceipt";
   @Autowired
   private MemberOrderMapper memberOrderMapper;
    public boolean verifyReceipt(String receiptData, String orderId)
    {
        try {
            JSONObject requestJson  = new JSONObject();
            requestJson .put("receipt-data", receiptData);
            // 可选：共享密钥（订阅类应用需要）
//            requestJson.put("password", "your_shared_secret");
            String response= HttpClientUtil.postJson(APPLE_PRODUCTION_URL, requestJson.toString());
            JSONObject result = new JSONObject(response);
            int status = result.getInt("status");

            // 3. 若生产环境失败且状态码 21007 → 切换到沙箱环境
            if (status == 21007) {
                response = HttpClientUtil.postJson(APPLE_SANDBOX_URL, requestJson.toString());
                result = new JSONObject(response);
                status = result.getInt("status");
                return true;

            }
            if(status==0){
                JSONObject receipt = result.getJSONObject("receipt");
                String productId = receipt.getJSONArray("in_app")
                        .getJSONObject(0)
                        .getString("product_id");
                // 更新订单
                updateOrderStatus(orderId, productId);
            }else {
                return false;
            }

        }catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }

        return false;
    }
    private void updateOrderStatus(String orderId, String productId) {
        MemberOrder order = memberOrderMapper.selectById(orderId);
        if (order != null && order.getStatus().equals(PayStatus.PENDING.getDescription())) {
            order.setStatus(PayStatus.SUCCESS.getDescription());
            order.setUpdatedTime(LocalDateTime.now());
            order.setPlanType(productId);
            memberOrderMapper.updateById(order);
        }
    }

    private void markOrderFailed(String orderId, int reason) {
        MemberOrder order = memberOrderMapper.selectById(orderId);
        if (order != null && order.getStatus().equals(PayStatus.FAIL.getDescription())) {
            order.setStatus(PayStatus.FAIL.getDescription());
            order.setUpdatedTime(LocalDateTime.now());
            memberOrderMapper.updateById(order);
        }
    }


}
